package com.dnr.arch.kernel.services.persistence;

import java.io.InputStream;
import java.util.Iterator;
import java.util.Properties;


import com.dnr.arch.kernel.KernelConstants;
import com.dnr.arch.kernel.api.InterfaceToPersistence;
import com.dnr.arch.kernel.api.factory.KernalFactoryInterface;
import com.dnr.arch.kernel.exceptions.KernelInitializationException;

public class PersistenceFactory implements KernalFactoryInterface{

	private static PersistenceFactory instance = null;
	
	private PersistenceFactory(){}
	
	public static PersistenceFactory getInstance(){
		if(instance==null){
			return new PersistenceFactory();
		}
		return instance;
	}
	
	
	public boolean initialize() throws KernelInitializationException{
		System.out.println("///////Initializing Persistence Drivers");
		initPersistenceDrivers();
		return true;
	}
	
	public static void initPersistenceDrivers(){
		try{
		Properties properties = new Properties();
		InputStream is = PersistenceFactory.class.getClassLoader()
	            .getResourceAsStream(PersistenceFactory.class.getPackage().getName().replaceAll("\\.", "/")+"/persistence.properties");
		    properties.load(is);
		
		
		for(Iterator i = properties.values().iterator();i.hasNext();){
			Class cls = PersistenceFactory.class.getClassLoader().loadClass((String)i.next());
			cls.getMethod(KernelConstants.INIT_METH_NAME, null).invoke(null, null);
		}
		}
		 catch (Exception e) {
			 e.printStackTrace();
		}
	
	}

	

	public static InterfaceToPersistence getPersistenceDriver(String driver) {
		if(driver.equals(KernelConstants.JPA_DRIVER)){
			return JPAPersistenceDriver.getInstance();
		}
		return null;
	}
}
